package com.xpxrule.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xpxrule.dataobject.req.ModelItemQueryReq;
import com.xpxrule.mapper.ModelItemMapper;
import com.xpxrule.dataobject.biz.model.ReturnResponse;
import com.xpxrule.dataobject.dao.ModelItem;
import com.xpxrule.dataobject.vo.ModelItemVo;
import com.xpxrule.util.ModelConvertUtil;
import com.xpxrule.service.ModelItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ModelItemServiceImpl implements ModelItemService {
    @Autowired
    private ModelItemMapper modelItemMapper;
    @Override
    public ReturnResponse insert(ModelItemVo vo) {
        boolean isExist = verifyDbUnique(vo);
        if (!isExist) {
            return ReturnResponse.fail("The unique verification failed. The new data already exists in the database.");
        }
        ModelItem dao = ModelConvertUtil.convertModelItemVoToModelItem(vo);
        int count = modelItemMapper.insert(dao);
        return ReturnResponse.success(count);
    }

    @Override
    public ReturnResponse delete(Long id) {
        boolean isExist = verifyDbExistById(id);
        if (!isExist) {
            return ReturnResponse.fail("The data does not exist in the database.");
        }
        ModelItem modelItem = modelItemMapper.selectById(id);
        modelItem.setIsDeleted(new Date());
        int count = modelItemMapper.updateById(modelItem);
        return ReturnResponse.success(count);
    }

    @Override
    public ReturnResponse update(ModelItemVo vo) {
        boolean isExist = verifyDbExistById(Long.valueOf(vo.getId()));
        if (!isExist) {
            return ReturnResponse.fail("The data does not exist in the database.");
        }
        ModelItem old = modelItemMapper.selectById(vo.getId());
        ModelConvertUtil.fillModelItemFromModelItemVo(old, vo);
        int count = modelItemMapper.updateById(old);
        return ReturnResponse.success(count);
    }

    @Override
    public ReturnResponse<List<ModelItemVo>> selectList(ModelItemQueryReq req) {
        QueryWrapper<ModelItem> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(req.getModelKey())) {
            wrapper.eq(ModelItem.COLUMN.MODEL_KEY, req.getModelKey());
        }
        if (!StringUtils.isEmpty(req.getFieldKey())) {
            wrapper.like(ModelItem.COLUMN.FIELD_KEY, req.getFieldKey());
        }
        if (!StringUtils.isEmpty(req.getFieldName())) {
            wrapper.like(ModelItem.COLUMN.FIELD_NAME, req.getFieldName());
        }
        if (!ObjectUtils.isEmpty(req.getIsEnable())) {
            wrapper.eq(ModelItem.COLUMN.IS_ENABLE, req.getIsEnable());
        }
        wrapper.isNull(ModelItem.COLUMN.IS_DELETED);
        List<ModelItem> list = modelItemMapper.selectList(wrapper);
        List<ModelItemVo> resultList = list.stream()
                .map(ModelConvertUtil::convertModelItemToModelItemVo)
                .collect(Collectors.toList());
        return new ReturnResponse<>(resultList);
    }

    @Override
    public List<ModelItem> getModelItemsByModelKey(String modelKey) {
        QueryWrapper<ModelItem> wrapper = new QueryWrapper<>();
        wrapper.eq(ModelItem.COLUMN.MODEL_KEY, modelKey);
        wrapper.isNull(ModelItem.COLUMN.IS_DELETED);
        wrapper.eq(ModelItem.COLUMN.IS_ENABLE, 0);
        List<ModelItem> modelItems = modelItemMapper.selectList(wrapper);
        return modelItems;
    }

    @Override
    public ModelItem getModelItemsByModelKeyAndFieldKey(String modelKey, String fieldKey) {
        QueryWrapper<ModelItem> wrapper = new QueryWrapper<>();
        wrapper.eq(ModelItem.COLUMN.MODEL_KEY, modelKey);
        wrapper.eq(ModelItem.COLUMN.FIELD_KEY, fieldKey);
        wrapper.isNull(ModelItem.COLUMN.IS_DELETED);
        List<ModelItem> list = modelItemMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(list) || list.size() != 1) {
            throw new RuntimeException("The data does not exist in the database.");
        }
        return list.get(0);
    }

    private boolean verifyDbExistById(Long id) {
        QueryWrapper<ModelItem> wrapper = new QueryWrapper<>();
        wrapper.eq(ModelItem.COLUMN.ID, id);
        wrapper.isNull(ModelItem.COLUMN.IS_DELETED);
        Long count = modelItemMapper.selectCount(wrapper);
        return count == 1;
    }

    /**
     * 根据模型key字段key逻辑删除字段判定唯一性
     * @param vo
     * @return
     */
    private boolean verifyDbUnique(ModelItemVo vo) {
        QueryWrapper<ModelItem> wrapper = new QueryWrapper<>();
        wrapper.eq(ModelItem.COLUMN.MODEL_KEY, vo.getModelKey());
        wrapper.eq(ModelItem.COLUMN.FIELD_KEY, String.format(ModelConvertUtil.MODEL_ITEM_KEY_FORMAT, vo.getModelKey(), vo.getFieldKey()));
        wrapper.isNull(ModelItem.COLUMN.IS_DELETED);
        Long count = modelItemMapper.selectCount(wrapper);
        return count == 0;
    }
}
